<template>
    <Index :type='1'>
        <div :class='$style.ctr'>
            <a-input placeholder='手机号码' size='large' v-model:value='formData.username' @focus='focus'>
                <template #prefix><UserOutlined :class='$style.inputprefix' /></template>
            </a-input>
        </div>
        <div class='m-t-30' :class='$style.ctr'>
            <a-input placeholder='登录密码' type='password' size='large' v-model:value='formData.password' @focus='focus'>
                <template #prefix><LockOutlined :class='$style.inputprefix' /></template>
            </a-input>
        </div>
        <div v-show='showError' class='m-t-20'>
            <a-alert :message='errorMsg' type='warning' show-icon />
        </div>
        <div class='m-t-30'>
            <a-button type='primary' size='large' block :loading='loading' @click='login'>登 录</a-button>
        </div>
        <div class='text-right m-t-20'>
            <router-link replace to='/forget'>忘记密码</router-link>
        </div>
    </Index>
</template>


<script lang='ts' setup>
    import Index from './index.vue'
    import { UserOutlined, LockOutlined } from '@ant-design/icons-vue';
    import { reactive, ref } from '@vue/reactivity';
    import { loginApi } from '@/api/login'
    import { verifyMobile } from '@/utils'
    import { useStore } from 'vuex';
import { useRoute, useRouter } from 'vue-router';
    

    const $store = useStore()
    const router =  useRouter()
    const route = useRoute()

    const loading = ref(false)
    const showError = ref(false)
    const errorMsg = ref('')

    const formData = reactive({
        username : route.query.mobile ? route.query.mobile : '',
        password : '',
        type : 'account'
    })

    function focus() {
        showError.value = false
    }

    async function login() {
        if(formData.username === '') {
            errorMsg.value = '请填写手机号码'
            showError.value = true
            return
        }

        if(formData.password === '') {
            errorMsg.value = '请填写登录密码'
            showError.value = true
            return
        }

        if(!verifyMobile(formData.username)) {
            errorMsg.value = '手机号码不正确'
            showError.value = true
            return
        }

        
        loading.value = true
        const res = await loginApi({...formData, mobile : formData.username})
        loading.value = false
        if(res.success) {
            await $store.dispatch('login', res.data)
            $store.dispatch('msgCount')
            if(route.query.redirect) {
                const redirect = decodeURIComponent(route.query.redirect as string)
                router.replace({
                    path : redirect
                })
            }else {
                router.replace('/')
            }
        }else {
            errorMsg.value = res.message
            showError.value = true
        }

    }

</script>

<style module lang='scss' src='./style.scss'></style>